﻿using System;
using System.Collections.Generic;
using System.Linq;
using NHibernate.Mapping.ByCode;
using Xenta.Enums;
using Xenta.Utils;

namespace Xenta.Entities
{
    /// <summary>
    /// Represents the payment entity.
    /// </summary>
    /// <remarks><pre>
    /// The entity regarding the disclosure level.
    /// 
    /// + Entire
    ///  + Extended
    ///   | - Attributes(of the Extended level)
    ///   + Base
    ///    | - Invoice(of the Keys level)
    ///    | - Customer(of the Base level)
    ///    | - ProcessorID
    ///    | - RefundAmount
    ///    | - Flags
    ///    | - Flags
    ///    | - UpdatedOn
    ///    | - CreatedOn
    ///    + Keys
    ///     | - Guid
    ///     + Primary
    ///      | - EntityID
    /// 
    /// Note: upper level includes lower level.
    /// </pre></remarks>
    public class PaymentEntity : AuditableEntity
    {
        #region Fields

        private ICollection<PaymentAttributeEntity> _attributes;

        #endregion

        #region Ctors

        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public PaymentEntity()
        {
            _attributes = new List<PaymentAttributeEntity>();
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets or sets the customer.
        /// </summary>
        public virtual CustomerEntity Customer
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the invoice.
        /// </summary>
        public virtual InvoiceEntity Invoice
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the processor global unique identifier.
        /// </summary>
        public virtual Guid ProcessorID
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the global unique identifier.
        /// </summary>
        public virtual Guid Guid
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the amount.
        /// </summary>
        public virtual decimal Amount
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the handling fee.
        /// </summary>
        public virtual decimal HandlingFee
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the flags.
        /// </summary>
        public virtual PaymentFlags Flags
        {
            get;
            set;
        }

        #endregion

        #region Collections

        /// <summary>
        /// Gets or sets the collection of attributes.
        /// </summary>
        public virtual ICollection<PaymentAttributeEntity> Attributes
        {
            get
            {
                return _attributes;
            }
            set
            {
                _attributes = value;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Gets the attribute value.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns>The attribute value.</returns>
        public virtual string Attribute(string key)
        {
            if(String.IsNullOrWhiteSpace(key))
                return String.Empty;
            var attribute = _attributes.SingleOrDefault(x => x.Key.Equals(key));
            if(attribute == null)
                return String.Empty;
            return attribute.Value;
        }

        /// <summary>
        /// Gets the attribute value as the type T.
        /// </summary>
        /// <typeparam name="T">The type to return.</typeparam>
        /// <param name="key">The attribute key.</param>
        /// <returns>The attribute value as the type T.</returns>
        public virtual T Attribute<T>(string key)
        {
            return StringHelper.ParseAs<T>(Attribute(key));
        }

        #endregion

        #region Utilities

        protected override void Disclose(IDictionary<String, Object> obj,
            DisclosureLevel level,
            IDictionary<String, String> options)
        {
            base.Disclose(obj, level, options);
            if(level >= DisclosureLevel.Keys)
                obj["Guid"] = Guid;
            if(level >= DisclosureLevel.Base)
            {
                obj["Invoice"] = Invoice.Disclose(DisclosureLevel.Keys, options);
                obj["Customer"] = Customer.Disclose(DisclosureLevel.Base, options);
                obj["ProcessorID"] = ProcessorID;
                obj["Amount"] = Amount;
                obj["HandlingFee"] = HandlingFee;
                obj["Flags"] = Flags.ToString();
            }
            if(level >= DisclosureLevel.Extended)
                obj["Attributes"] = Attributes.Map(x => x.Disclose(DisclosureLevel.Extended, options));
        }

        #endregion
    }

    /// <summary>
    /// The entity NHibernate mapping.
    /// </summary>
    public class PaymentMapping : EntityMapping<PaymentEntity>
    {
        /// <summary>
        /// Initializes a new class instance.
        /// </summary>
        public PaymentMapping()
        {
            Table("fwk_Payments");
            Id(x => x.EntityID, m =>
            {
                m.Column("PaymentID");
                m.Generator(Generators.Identity);
            });
            ManyToOne(x => x.Customer, m =>
            {
                m.Column("CustomerID");
                m.ForeignKey("FK_fwk_Payments_fwk_Customers");
                m.NotNullable(true);
                m.Fetch(FetchKind.Join);
            });
            ManyToOne(x => x.Invoice, m =>
            {
                m.Column("InvoiceID");
                m.ForeignKey("FK_fwk_Payments_fwk_Invoices");
                m.NotNullable(true);
                m.Fetch(FetchKind.Join);
            });
            Property(x => x.ProcessorID, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.Guid, m =>
            {
                m.Unique(true);
                m.Index("IX_fwk_Payments");
                m.NotNullable(true);
            });
            Property(x => x.Amount, m =>
            {
                m.Precision(19);
                m.Scale(4);
                m.NotNullable(true);
            });
            Property(x => x.HandlingFee, m =>
            {
                m.Precision(19);
                m.Scale(4);
                m.NotNullable(true);
            });
            Property(x => x.Flags, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.CreatedOn, m =>
            {
                m.NotNullable(true);
            });
            Property(x => x.UpdatedOn, m =>
            {
                m.NotNullable(true);
            });
            Bag(x => x.Attributes, m =>
            {
                m.Table("fwk_GenericAttributes");
                m.Key(k =>
                {
                    k.Column("HolderID");
                    k.NotNullable(true);
                });
                m.Inverse(true);
                m.BatchSize(10);
            },
            a =>
            {
                a.OneToMany();
            });
        }
    }
}
